<template>
	<view>
		<view-head Title="调整目标" :isShowR="false"></view-head>
		<view class="view-content">
			<view class="subTitle">
				固定目标
			</view>
			<view class="list">
				<view class="item" @click="showPopFn(1)">
					<image src="@/static/img/index/hd1.png" mode=""></image>
					<view class="title">
						目标步数
					</view>
					<view class="input-box _df _jb _ac">
						{{data.steps}}
						<view class="dw">
							步/天<u-icon class="ml10" name="arrow-right" color="#aaa" size="28"></u-icon>
						</view>
					</view>
				</view>
				<view class="item" @click="showPopFn(2)">
					<image src="@/static/img/index/hd2.png" mode=""></image>
					<view class="title">
						活动热量
					</view>
					<view class="input-box _df _jb _ac">
						{{data.heat}}
						<view class="dw">
							千卡/天<u-icon class="ml10" name="arrow-right" color="#aaa" size="28"></u-icon>
						</view>
					</view>
				</view>
				<!-- <view class="item" @click="showPopFn(3)">
					<image src="@/static/img/index/hd3.png" mode=""></image>
					<view class="title">
						运动时长
					</view>
					<view class="input-box _df _jb _ac">
						{{data.motionDuration}}
						<view class="dw">
							分钟/天<u-icon class="ml10" name="arrow-right" color="#aaa" size="28"></u-icon>
						</view>
					</view>
				</view> -->
				<view class="item" @click="showPopFn(4)">
					<image src="@/static/img/index/hd4.png" mode=""></image>
					<view class="title">
						距离
					</view>
					<view class="input-box _df _jb _ac">
						{{data.distance}}
						<view class="dw">
							米/天<u-icon class="ml10" name="arrow-right" color="#aaa" size="28"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="subTitle">
				通知提醒
			</view>
			<view class="switch _df _jb _ac">
				<view class="title">
					每日目标达成提醒
				</view>
				<u-switch v-model="checked" @change="switchChange" size="56" active-color="#6387FF" inactive-color="#eee"></u-switch>
			</view> -->
		</view>
		<u-select :title="selectTitle" v-model="showPop" :default-value="defaultValue" :list="selectList" @confirm="confirm"></u-select>
		<u-calendar active-bg-color="#FF4651" v-model="show" :mode="mode" @change="change"></u-calendar>
		<send-order ref="blue" @blueBack="blueBack"></send-order>
	</view>
</template>

<script>
	let timer,timer2;
	export default {
		data() {
			return {
				data:{
					id:null,
					steps:null,
					heat:null,
					motionDuration:null,
					distance:null,
				},
				show:false,
				mode:'date',
				checked:true,
				showPop:false,
				selectList:[],
				selectTitle:'目标步数',
				type:1,
				isJoin:false,
				deviceId: '',
				serviceId: '',
				writeId: '',
				notifyUuid: '',
				orderVal:'ad0b0000',
				orderT:'0x0b',
				defaultValue:[]
			};
		},
		watch:{
			type(v){
				this.type = v
			}
		},
		onLoad() {
			
		},
		onShow() {
			this.getData()
			
		},
		methods:{
			getData(){
				let that = this
				uni.$_get({
					url: "getUserTarget",
					that: that,
					success(res) {
						console.log(res)
						let _data = res.data;
						if(res.code == 0){
							that.data.id = _data.id
							that.data.steps = _data.steps
							that.data.heat = _data.heat / 1000
							that.data.motionDuration = _data.motionDuration
							that.data.distance = _data.distance
							// that.getWatch()
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			getWatch(){
				let that = this;
				uni.$_get({
					url: "get-watch",
					that: that,
					success(res) {
						let _data = res.data;
						if(res.code == 0){
							if(_data){
								that.deviceId = _data.deviceId
								that.notifyUuid = _data.notifyUuid
								that.serviceId = _data.serviceId
								that.writeId = _data.writeId
								let step = (that.data.steps).toString(16)
								let heat = (that.data.heat).toString(16)
								let distance = (that.data.distance / 1000).toString(16)
								that.orderVal = 'da0a080000002ee0001e0001'
								that.writeFn()
								console.log(step,111)
								console.log(heat)
								console.log(distance)
							}else{
								uni.showToast({
									title:'设备未连接！'
								})
							}
						}
						
					},
					fail(err) {
						
					},
				});
			},
			padHexString(hexStr,length) {
			  let paddedHex = Number(`0x${hexStr}`).toString(16).padStart(length, '0');
			  return paddedHex;
			},
			
			blueBack(e,ids){
				this.isJoin = e
				this.deviceId = ids.deviceId
				this.serviceId = ids.serviceId
				this.writeId = ids.writeId
				this.notifyUuid = ids.notifyUuid
				// this.getData()
				
			},
			
			dowrite(){
				//处理步数指令
				let step16 = (this.data.steps).toString(16)//转为16进制
				let newStep16 = this.padHexString(step16,8)//补位0为8位
				let stepArr = uni.$_parseStrtoArr(newStep16, 2).reverse()//反转拆分好的数组
				let newStep = stepArr.join('')//最终指令
				//处理热量指令
				let heat16 = (this.data.heat).toString(16)//转为16进制
				let newHeat16 = this.padHexString(heat16,4)//补位0为4位
				let heatArr = uni.$_parseStrtoArr(newHeat16, 2).reverse()//反转拆分好的数组
				let newHeat = heatArr.join('')//最终指令
				//处理距离指令
				let distance16 = (this.data.distance / 1000).toString(16)//转为16进制
				let newDistance16 = this.padHexString(distance16,4)//补位0为4位
				let distanceArr = uni.$_parseStrtoArr(newDistance16, 2).reverse()//反转拆分好的数组
				let newDistance = distanceArr.join('')//最终指令
				this.orderVal = 'da0a0800' + newStep + newHeat +newDistance
				if(this.isJoin){
					timer = setInterval(()=>{
						this.writeFn()
						
					},1000)
				}
			},
			writeFn() {
				var that = this
				let crc = uni.$_getCrc_16_ibm(this.orderVal)
				let val = this.orderVal + crc
				console.log(val, '发送的指令')
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("写入成功", res)
						
						that.startNotice()
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading()
					},
					// complete: function() {
					// 	console.log("调用结束");
			
					// }
				})
			},
			
			//订阅蓝牙消息返回
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: this.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// that.listenValueChange()
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								let resHex = uni.$_ab2hex(result.value)
								console.log('设备返回原始数据', resHex)
								that.dataObj = uni.$_parse_blue_response(resHex, 2)
								if(that.dataObj.Head === 'da' && that.dataObj.Cmd === "8a" ) {
									// that.dataToArr(that.dataObj.Data,that.orderDataList)
									clearInterval(timer)
								}
								
							}
						})
			
					},
					fail(err) {
						console.log(err)
						uni.hideLoading()
					}
				})
			},
			//返回的数据拆分
			dataToArr(dataList,orderDataList){
				orderDataList.forEach((item,index) =>{
					if(index == 0){
						item.dataLen = item.len
						item.value  = dataList.slice(0,item.dataLen)
					}else{
						item.dataLen = orderDataList[index-1].dataLen +orderDataList[index].len
						if(item.len>=2){
							let itemArr = dataList.slice(orderDataList[index-1].dataLen,item.dataLen).reverse()
							let str = itemArr.join('')
							item.value = str
							item.data = uni.$_hex2int(str)
						}else{
							let itemArr = dataList.slice(orderDataList[index-1].dataLen,item.dataLen)
							let str = itemArr.join('')
							item.value = str
							item.data = uni.$_hex2int(str)
							
						}
					}
				})
				// uni.showToast({
				// 	title:'获取成功！',
				// 	icon:'success'
				// })
				uni.hideLoading()
			},
			
			addData(){
				let that = this
				let page = {
					id:this.data.id,
					steps:this.data.steps,
					heat:this.data.heat * 1000,
					motionDuration:this.data.motionDuration,
					distance:this.data.distance,
					messageStatus:0
				}
				uni.$_post({
					url: "targetAddOrUpdate",
					that: that,
					params: page,
					success(res) {
						console.log(res)
						if(res.code == 0){
							
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			saveBack(){
				
			},
			change(e){
				
			},
			switchChange(e){
				
			},
			showPopFn(e){
				this.showPop = true
				this.selectList = []
				this.defaultValue = []
				switch (e){
					case 1:
					this.type = 1
					this.selectTitle = '目标步数'
					for(let i=1;i<=40;i++){
						let val = 500 * i
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.selectList.push(obj)
					}
					let index = this.selectList.find((item) => item.value==this.data.steps).index
					this.defaultValue = [index-1]
					break
					case 2:
					this.type = 2 
					this.selectTitle = '活动热量'
					for(let i=1;i<=100;i++){
						let val = i * 10
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.selectList.push(obj)
					}
					let index2 = this.selectList.find((item) => item.value==this.data.heat).index
					this.defaultValue = [index2-1]
					break 
					case 3:
					this.type = 3
					this.selectTitle = '运动时长'
					for(let i=1;i<=24;i++){
						let val = i * 5
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.selectList.push(obj)
					}
					let index3 = this.selectList.find((item) => item.value==this.data.motionDuration).index
					this.defaultValue = [index3-1]
					break
					case 4:
					this.type = 4
					this.selectTitle = '距离'
					for(let i=1;i<=10;i++){
						let val = i * 1000
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.selectList.push(obj)
					}
					let index4 = this.selectList.find((item) => item.value==this.data.distance).index
					this.defaultValue = [index4-1]
					break 
					
				}
			},
			confirm(e){
				console.log(e)
				switch (this.type){
					case 1:
					this.data.steps = e[0].value
					break
					case 2:
					this.data.heat = e[0].value
					break 
					case 3:
					this.data.motionDuration = e[0].value
					break
					case 4:
					this.data.distance = e[0].value
					break 
					
				}
				this.addData()
				this.dowrite()
				
			}
		},
	}
</script>

<style lang="scss" scoped>
	/deep/.u-btn--primary{
		background-color: #FF4651;
		border-color: #FF4651;
	}
	/deep/.uni-picker-view-indicator{
		height: 100rpx;
		line-height: 100rpx;
	}
	/deep/.u-select__body__picker-view__item{
		height: 100rpx;
		line-height: 100rpx;
		font-size: 44rpx;
		color: #000;
		font-family: $uni-font-family-Bold;
	}
	/deep/.u-select__header__title{
		font-size: 38rpx;
		color: #000;
		font-family: $uni-font-family-Medium;
	}
	/deep/.u-select__header__cancel{
		width: 150rpx;
		height: 70rpx;
		background: #edeff0;
		border-radius: 35rpx;
		text-align: center;
		line-height: 70rpx;
		font-size: 30rpx;
		color: #000;
		font-family: $uni-font-family-Medium;
	}
	/deep/.u-select__header__confirm{
		width: 150rpx;
		height: 70rpx;
		background: #6387FF;
		border-radius: 35rpx;
		text-align: center;
		line-height: 70rpx;
		font-size: 30rpx;
		color: #fff !important;
		font-family: $uni-font-family-Medium;
	}
	/deep/.u-select__header{
		height: auto;
		padding: 20rpx 30rpx 0;
	}
.view-content{
	padding: 0 50rpx 80rpx;
	.time-box{
		margin-bottom: 60rpx;
		.name{
			font-size: 34rpx;
			font-family: $uni-font-family-Bold;
			color: #000;
		}
		.time{
			font-size: 28rpx;
			font-family: $uni-font-family-Medium;
			color: #aaa;
		}
	}
	.subTitle{
		font-size: 24rpx;
		font-family: $uni-font-family-Medium;
		color: #888;
		margin-bottom: 24rpx;
	}
	.switch{
		.title{
			font-size: 34rpx;
			font-family: $uni-font-family-Bold;
			color: #000;
		}
	}
	.list{
		padding-bottom: 40rpx;
		margin-bottom: 40rpx;
		border-bottom: 1rpx solid #eeeeee;
		.item{
			height: 130rpx;
			background: #ffffff;
			border-radius: 24rpx;
			box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.10); 
			padding: 0 30rpx 0 30rpx;
			margin-bottom: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			image{
				width: 60rpx;
				height: 60rpx;
				margin-right: 24rpx;
			}
			.title{
				font-size: 28rpx;
				font-family: $uni-font-family-Bold;
				color: #171717;
				margin-right: auto;
			}
			.input-box{
				font-size: 32rpx;
				font-family: $uni-font-family-Heavy;
				color: #111;
			}
			.dw{
				font-size: 28rpx;
				font-family: $uni-font-family-Medium;
				color: #aaa;
				margin-left: 10rpx;
				// margin-left: 10rpx;
			}
			
		}
	}
}
</style>
